using UnityEngine;

using System.Collections;


public class Button : MonoBehaviour {
	public Texture2D _normalTexture;
	public Texture2D _overTexture;
	public Texture2D _downTexture;
	public Texture2D _diableTexture;

	
	public Color _nomalTextColor = Color.white;
	public Color _overTextColor = Color.yellow;
	public Color _downTextColor = Color.green;
	public Color _disableTextColor = Color.gray;

	public Rect _rect = new Rect(0, 0, 128, 32);

	enum BUTTON_STATE {
		INVALID = 0,
		NORMAL,
		OVER,
		DOWN,
		DISABLE,
	};

	enum MOUSE_BUTTON {
		LEFT = 0,
		RIGHT,
		MIDDLE,
	};

	BUTTON_STATE _state = BUTTON_STATE.INVALID;
	
	// Use this for initialization
	void Start () {
		transform.position = Vector3.zero;
		transform.localScale = Vector3.zero;
		
		gameObject.AddComponent("GUITexture");
		
		// 이 컨트롤의 부모가 있다면 부모의 _rect 를 얻어와서 계산에 포함시켜야한다.
		// UI 처리는 전부 inset 으로 할 생각인데 이런 계층구초의 처리가 골치아프다.
		
		_rect.y = Screen.height - _rect.y - _normalTexture.height;
		guiTexture.pixelInset = _rect;

		SetState(BUTTON_STATE.NORMAL);
	}
	
	// Update is called once per frame
	void Update () {
		if (_state == BUTTON_STATE.DISABLE) {
			return;
		}
		
		UpateState();
	}
	
	void UpateState() {
		BUTTON_STATE state = BUTTON_STATE.NORMAL;

		bool isHit = guiTexture.HitTest(Input.mousePosition);
		if (isHit) {
			if (Input.GetMouseButton((int)MOUSE_BUTTON.LEFT)) {	// down
				state = BUTTON_STATE.DOWN;
			} else {	// over
				state = BUTTON_STATE.OVER;
			}
		}
		
		SetState(state);
	}
	
	void SetState(BUTTON_STATE state) {
		if (_state == state) {
			return;
		}
		
		_state = state;
		switch (_state) {
		case BUTTON_STATE.NORMAL:
			guiTexture.texture = _normalTexture;
			guiText.material.color = _nomalTextColor;
			guiText.pixelOffset = GetDefaultPixelOffset();
			break;

		case BUTTON_STATE.OVER:
			guiTexture.texture = _overTexture;
			guiText.material.color = _overTextColor;
			guiText.pixelOffset = GetDefaultPixelOffset();
			break;

		case BUTTON_STATE.DOWN:
			guiTexture.texture = _downTexture;
			guiText.material.color = _downTextColor;
			Vector2 offset = GetDefaultPixelOffset();
			offset.x += 0.5f;
			offset.y -= 1f;
			guiText.pixelOffset = offset;
			break;

		case BUTTON_STATE.DISABLE:
			guiTexture.texture = _diableTexture;
			guiText.material.color = _disableTextColor;
			guiText.pixelOffset = GetDefaultPixelOffset();
			break;
			
		default:
			print ("invalid button state");
			break;
		}
	}

	Vector2 GetDefaultPixelOffset()
	{
		Vector2 offset = _rect.center;
		offset.y += 4;
		
		return offset;
	}
}
